import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class CsvWriter {
	private AttributeHandler attributeHandler = new AttributeHandler();
	private final String MESSAGE_ERROR_WRITE_TO_CSV = "writeToCSV function error!";
	private final String MESSAGE_ERROR_CLEAR_CSV_FILE = "Error clearing CSV file!";
	
	public void clear() {
		clearCSV();
	}
	
	public void write(String oneTaskString, ArrayList<String> listOfTaskString) {
		writeTaskToCSV(oneTaskString, listOfTaskString);
	}
	
	public void write(ArrayList<Task> listOfTask) {
		ArrayList<String> listOfTaskString = attributeHandler.convertTaskToString(listOfTask);
		writeTaskToCSV(null, listOfTaskString);
	}
	
	private void writeTaskToCSV(String oneTaskString, ArrayList<String> listOfTaskString) {
	    if (listOfTaskString == null) {
	      appendlNewTaskToCSV(oneTaskString);
	    } else {
	      clearThenAppendListOfTaskToCSV(listOfTaskString);
	    }
	  }
	
	private void appendlNewTaskToCSV(String oneTaskString) {
	    try {
	      FileWriter fileWriter = new FileWriter(FileManager.getFileName(), true);
	      PrintWriter printWriter = new PrintWriter(fileWriter);

	      printWriter.println(oneTaskString.trim());
	      printWriter.close();
	    } catch (IOException e) {
	      System.out.println(MESSAGE_ERROR_WRITE_TO_CSV);
	    }
	  }
	
	private void clearThenAppendListOfTaskToCSV(ArrayList<String> listOfTaskString) {
	    clearCSV();
	    appendListOfTaskToCSV(listOfTaskString);
	}
	
	private void clearCSV() {
		try {	
			FileWriter fileWriter = new FileWriter(FileManager.getFileName(), false);
			PrintWriter printWriter = new PrintWriter(fileWriter, false);
				
			printWriter.flush();
			printWriter.close();
			fileWriter.close();
		} catch(IOException e) {
			System.out.println(MESSAGE_ERROR_CLEAR_CSV_FILE);
		}	
	}
	
	private void appendListOfTaskToCSV(ArrayList<String> listOfTaskString) {
	    try {
	      FileWriter fileWriter = new FileWriter(FileManager.getFileName(), true);
	      PrintWriter printWriter = new PrintWriter(fileWriter);

	      for(int i = 0; i < listOfTaskString.size(); i++) {
	        printWriter.println(listOfTaskString.get(i));
	      }
	      
	      printWriter.close();
	    } catch (IOException e) {
	      System.out.println(MESSAGE_ERROR_WRITE_TO_CSV);
	    }  
	}
}